﻿using System.IO;
using System.Windows;
using iTextSharp.text;
using iTextSharp.text.pdf;
using ThePresenter.Windows;


namespace ThePresenter.IO
{
	public class Pdf : AbstractFormat, IWriter
	{
		#region IFormat Members
		/// <summary>
		/// Gets the filter that is shown in the <see cref="Microsoft.Win32.OpenFileDialog"/> and <see cref="Microsoft.Win32.SaveFileDialog"/> dialogs. If is null, this format does not support writing or reading to / from file. Can be null.
		/// </summary>
		/// <value>The filter shown in the dialogs.</value>
		public override string Filter
		{
			get
			{
				return "Portable Document Format (*.pdf)|*.pdf";
			}
		}

		/// <summary>
		/// Gets a value indicating whether this format supports progress reporting.
		/// </summary>
		/// <value><c>true</c> if this format supports progress reporting; otherwise, <c>false</c>.</value>
		public override bool SupportsProgressReporting
		{
			get { return true; }
		}
		#endregion


		#region IWriter Members
		/// <summary>
		/// Writes the specified presentation to the stream.
		/// </summary>
		/// <param name="config">The configuration object.</param>
		/// <param name="presentation">The presentation.</param>
		/// <param name="stream">The stream.</param>
		/// <exception cref="ThePresenter.WriteException"/>
		public void Write(DependencyObject config, Presentation presentation, Stream stream)
		{
			TotalSlides = presentation.Slides.Count;

			using (Document pdf = new Document())
			{
				PdfWriter.GetInstance(pdf, stream);

				pdf.SetMargins(0, 0, 0, 0);

				if (presentation.Slides.Count > 0)
					pdf.SetPageSize(new Rectangle((float)presentation.Slides[0].Size.Width, (float)presentation.Slides[0].Size.Height));

				pdf.Open();

				pdf.AddAuthor(presentation.Author);
				pdf.AddCreationDate();
				pdf.AddTitle(presentation.Title);

				for (int i = 0; i < presentation.Slides.Count; i++)
				{
					var slide = presentation.Slides[i];

					pdf.SetPageSize(new Rectangle((float)slide.Size.Width, (float)slide.Size.Height));
					pdf.NewPage();

					Image image = Image.GetInstance(slide.Canvas.GetThumbnailAsStream(slide.Size));
					pdf.Add(image);

					SlidesDone = i + 1;
				}

				pdf.Close();
			}
		}
		#endregion
	}
}
